﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.CrmContacto.Code;
using Web.Framework;
using Web.Framework.Config;
using System.Configuration;
using System.Text;
using CrmContacto.Contracts.Contracts;
using CrmContacto.WebApp.Code.InnerClasses;

namespace Web.CrmContacto.Account
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SiteMaster masterPage = (SiteMaster)this.Master;
                masterPage.MakeMenuVisible(false);
                //RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
                LoginUser.Authenticate += new AuthenticateEventHandler(LoginUser_Authenticate);

                ApiAuthConfigurationSection configuration = (ApiAuthConfigurationSection)ConfigurationManager.GetSection("ApiAuthConfigurationGroup/ApiAuthSecurityConfiguration");

                RegisterCompaniesIntoJS();

                BaseWebPage.ApplicationId = configuration.ApplicationId;

                var ctrl = (DropDownList)this.LoginUser.FindControl("CompanyCbo");
                ctrl.DataSource = WebServiceHelper.GetCompanies(BaseWebPage.ApplicationId);
                ctrl.DataValueField = "Id";
                ctrl.DataTextField = "Name";
                ctrl.DataBind();

                if (!this.IsPostBack)
                {
                    List<string> cookieCompany = HttpHelper.GetCookieValues(MiscClass.CookieCompany, this.Request);
                    if (cookieCompany.Count > 0)
                    {
                        ctrl.SelectedValue = cookieCompany[0];
                        this.hidCompany.Value = cookieCompany[0];
                    }
                }
                else
                {
                    ctrl.SelectedValue = this.hidCompany.Value;
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void RegisterCompaniesIntoJS()
        {
            // Tengo que registrar el array en javascript
            StringBuilder builder = new StringBuilder();
            string separador = string.Empty;
            builder.Append("<script type='text/javascript' >");
            builder.Append("var companies = [];");
            foreach (CompanyConfiguration companyConfiguration in BasePage.GetCompanyConfigurationList(this.Page))
            {
                //builder.AppendFormat("companies[{0}] = '{1}';", companyConfiguration.CompanyId, companyConfiguration.LogoImgFilePath);
                builder.AppendFormat("companies[{0}] = '{1}##{2}';", companyConfiguration.CompanyId, companyConfiguration.LogoImgFilePath, companyConfiguration.CssFilePath);
            }

            builder.Append("</script>");
            Page.ClientScript.RegisterStartupScript(typeof(string), "companias", builder.ToString());
        }

        private void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
        {
            try
            {
                var ctrl = (DropDownList)this.LoginUser.FindControl("CompanyCbo");
                ApiAuthConfigurationSection configuration = (ApiAuthConfigurationSection)ConfigurationManager.GetSection("ApiAuthConfigurationGroup/ApiAuthSecurityConfiguration");

                if (LoginUser.UserName == configuration.SuperAdminName && LoginUser.Password == configuration.SuperAdminPassword)
                {
                    e.Authenticated = true;
                    BaseWebPage.CompanyId = Convert.ToInt32(ctrl.SelectedValue);
                    BaseWebPage.IsAdmin = true;
                }
                else if (e.Authenticated = WebServiceHelper.Authenticate(BaseWebPage.ApplicationId, Convert.ToInt32(ctrl.SelectedValue), LoginUser.UserName, LoginUser.Password))
                {
                    BaseWebPage.CompanyId = Convert.ToInt32(ctrl.SelectedValue);
                    BaseWebPage.IsAdmin = false;
                }

                if (e.Authenticated)
                {
                    // seteo el nombre del usuario en el login
                    string displayName = LoginUser.UserName;
                    var adUser = WebServiceHelper.GetUsers(BaseWebPage.ApplicationId, BaseWebPage.CompanyId, LoginUser.UserName).SingleOrDefault();
                    if (adUser != null)
                    {
                        if (!String.IsNullOrEmpty(adUser.GivenName))
                        {
                            displayName = adUser.GivenName;
                        }
                    }

                    BaseWebPage.DisplayUserName = displayName;

                    HttpHelper.SetCookieValues(MiscClass.CookieCompany, this.Response, ctrl.SelectedValue, ctrl.SelectedItem.Text);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}
